/*
  ____        _                         _____
 |  _ \      | |                       / ____|
 | |_) | __ _| | __ _ _ __   ___ ___  | |     __ _ _ __
 |  _ < / _` | |/ _` | '_ \ / __/ _ \ | |    / _` | '__|
 | |_) | (_| | | (_| | | | | (_|  __/ | |___| (_| | |
 |____/ \__,_|_|\__,_|_| |_|\___\___|  \_____\__,_|_|
   _____           _           _   ____         __     __  _    _                 _     _
  / ____|         | |         | | |  _ \        \ \   / / | |  | |               | |   | |
 | |     ___  __ _| |_ ___  __| | | |_) |_   _   \ \_/ ___| |__| | __ _ _ __ ___ | | __| |
 | |    / _ \/ _` | __/ _ \/ _` | |  _ <| | | |   \   / _ |  __  |/ _` | '__/ _ \| |/ _` |
 | |___|  __| (_| | ||  __| (_| | | |_) | |_| |    | |  __| |  | | (_| | | | (_) | | (_| |
  \_____\___|\__,_|\__\___|\__,_| |____/ \__, |    |_|\___|_|  |_|\__,_|_|  \___/|_|\__,_|
                                          __/ |
                                         |___/
  Copyright (c) 2024 YeHarold
*/

#include "ButtonAndBattery.h"
#include "BuzzerSound.h"
#include "OneButton.h"
#include "RGBLED.h"

OneButton bnt(BUTTON_PIN, true);
uint16_t batteryVoltage;
void balanceCarPowerOn()
{
    digitalWrite(POWEREN_PIN, HIGH);
}

void balanceCarPowerOff()
{
    buzzer.play(powerOffID);
    rgb.TurnOff();
    digitalWrite(POWEREN_PIN, LOW);
}

void turnOffRGB()
{
    buzzer.play(powerOffledID);
    rgb.TurnOff();
}

void focSelfCheckCompleted()
{
    buzzer.play(S_BEEP);
}

void CheckBatteryVoltageForSafety()
{
    batteryVoltage = analogRead(BAT_ADC_PIN); //
    if (batteryVoltage < 3000)
    {
        buzzer.play(S_SIREN);
        // digitalWrite(POWEREN_PIN, LOW);
        // Serial.println(batteryVoltage );
    }
}

void ButtonEventTask(void *pvParameters)
{

    pinMode(POWEREN_PIN, OUTPUT);
    balanceCarPowerOn();

    buzzer.Init(BUZZER_PIN);
    buzzer.play(powerOnID);

    bnt.reset();
    bnt.attachLongPressStart(balanceCarPowerOff);
    bnt.attachClick(turnOffRGB);
    // bnt.attachDoubleClick(turnOffRGB);

    rgb.Initialize();

    for (;;)
    {
        bnt.tick();
        vTaskDelay(50);
    }
};

void BatteryVoltageCheckTask(void *pvParameters)
{
    pinMode(BAT_ADC_PIN, INPUT);
    for (;;)
    {
        CheckBatteryVoltageForSafety();
        vTaskDelay(50);
    }
};

void BNT_AND_PWR::startTask()
{

    xTaskCreatePinnedToCore(ButtonEventTask, "Button_Event", 2048, NULL, 2, NULL, 0);
    xTaskCreatePinnedToCore(BatteryVoltageCheckTask, "Battery_Voltage_Check", 2048, NULL, 5, NULL, 1);
};

BNT_AND_PWR ButtonAndPower;
